import  { useCallback, useEffect, useMemo, useState } from 'react';
import { Card, Select, Button, Space, Table, Modal, Tabs, Switch } from "antd";
import { SearchOutlined } from '@ant-design/icons';
import { deleteBindInfo, updateBindStatus, updateBindInfo, addBindInfo } from "../api/bind";
import Message from '@/components/Message';
import BindForm from '../components/BindForm';

import {state as states} from '@/stores/Merchant';
import {useSnapshot } from "valtio"
const Bind = () => {
    const state = useSnapshot(states);
    const [scoure,setScoure] = useState(0);
    const [title,setTitle] = useState("饿了么");

    interface FormType {
        _id?:string,
        account:string,    // 账号
        shopName: string,    // 店铺名称
        bindShop: string,    // 绑定店铺
        isorder: boolean,   // 是否接单
        istodelivery: boolean,    // 是否配送
        isbind: boolean,    // 是否绑定
        bindtime:number,    // 绑定时间
        failreason:string, // 失败原因
        phone: string,      // 手机号
        scoure: number,  // 来源
        linkid: string,    // 链接id

    }
    const [form, setForm] = useState<FormType>({ 

        account: "",    // 账号
        shopName: "",    // 店铺名称
        bindShop:"",    // 绑定店铺
        isorder:true,   // 是否接单
        istodelivery:true,    // 是否配送
        isbind:true,    // 是否绑定
        bindtime:Date.now(),    // 绑定时间
        failreason:"", // 失败原因
        phone:"",      // 手机号
        scoure: scoure    ,  // 来源
        linkid:'',    // 链接id
    });
    const [search,setSearch] = useState({
        shopName:""
    });
    const [modalShow, setModalShow] = useState(false);
    const [show, setShow] = useState(false);
    const [selectedBind, setSelectedBind] = useState<any>(null);

    const fetchBindList = useCallback(() => {
        states.getData6(search)
    }, [search]);

    useEffect(() => {
        fetchBindList();
    }, []);

    const handleSearch = () => {
        fetchBindList();
    };
    let bindData = useMemo(()=>{ 
        let data = state.bindList.filter((item:any)=>{
            return item.scoure === scoure
        })
        return data
    }, [state.bindList,scoure])
    const handleAdd = () => {
        addBindInfo(form).then((res: any) => {
            if (res.code === 200) {
                fetchBindList();
            }
        });
    };

    const handleUpdate = () => {
        updateBindInfo(form).then((res: any) => {
            if (res.code === 200) {
                fetchBindList();
            }
        });
    };
    //  删除品牌
    const handleDelete = () => {
        deleteBindInfo(selectedBind).then((res: any) => {
            if (res.code === 200) {
                fetchBindList();
            }
        });
    };

    const columns1 = [
        { title: "序号", dataIndex: 'key', key: 'key' },
        { title: title+"账号", dataIndex: 'account', key: 'account' },
        { title: title+"店铺名称", dataIndex: 'shopName', key: 'shopName' },
        { title: "店铺绑定", dataIndex: 'bindShop', key: 'bindShop' },
        {
            title: "是否接单",
            dataIndex: 'isorder',
            key: 'isorder',
            render: (_:any, record: any) => (
                <Space size="middle">
                    <Switch defaultChecked={record.isorder} onChange={async () => { 
                       await updateBindStatus({...record,id:2})
                        await fetchBindList();
                       await updateBindStatus({...record,id:1})
                        await fetchBindList();
                    }} />
                </Space>
            ),
        },
        {
            title: "是否发送订单到配送员APP",
            dataIndex: 'istodelivery',
            key: 'istodelivery',
            render: (record:any) => (
                <Space size="middle">
                    <Switch defaultChecked={record.istodelivery} onChange={async() => {
                      await updateBindStatus({ ...record, id: 2 })
                        await fetchBindList();


                     }} />
                </Space>
            ),
        },
        {
            title: "是否绑定",
            dataIndex: 'isbind',
            key: 'isbind',
            render: () => (
                <Space size="middle">
                    <a>点击绑定</a>
                </Space>
            ),
        },
        { title: "失败原因", dataIndex: 'failreason', key: 'failreason' },
        {
            title: "绑定的时间",
            dataIndex: 'bindtime',
            key: 'bindtime',
            render: () => (
                <Space size="middle">
                    2020-09-03 14:41:23


                </Space>
            ),
        },
        {
            title: "操作",
            dataIndex: 'action',
            key: 'action',
            render: (_:any, record: any) => (
                <Space size="middle">
                    <a onClick={() => {
                        setForm(record);
                        setModalShow(true);
                    }}>编辑</a>
                    <a className='color-red' onClick={() => {
                        setSelectedBind(record);
                        setShow(true);
                    }}>注销</a>
                </Space>
            ),
        }
    ];

    const info = {
        headTitle: "删除品牌确认",
        bodyTitle: `请确认是否删除品牌[${selectedBind?.brandName}]！`,
        bodyContent: "如果删除，该品牌下的所有关联将自动解除~",
    };

    return (
        <div className='m=auto w-[100%] m-t-5'>
            <Message info={info} show={show} setShow={setShow} callBack={handleDelete} />
            <Card title='品牌筛选' className='m-auto w-[90%] rounded-none p-0'>
                <div style={{ display: "flex", height: "30px", lineHeight: '30px', padding: 0 }}>
                    <p className='m-0 '>店铺名称：</p>
                    <Select
                        style={{marginRight:"10px",width:"200px"}}
                        defaultValue="请选择"
                        value={search.shopName}
                        onChange={async(e) => { 
                            setSearch({ shopName: e }) 
                        }}
                        options={[...state.shopCate]}
                    />
                    <Button
                        type="primary"
                        onClick={()=>{
                            handleSearch()
                        }}
                        className='rounded-none'
                        icon={<SearchOutlined />}
                    >
                        查询
                    </Button>
                </div>
            </Card>

            <Card className='w-[90%] m-auto mt-5 rounded-none'>
                <div className='flex justify-between items-center'>
                    <p>共有{bindData.length}条记录</p>

                    <Button
                        className='rounded-none'
                        type='primary'
                        onClick={() => 
                            {setModalShow(true)
                            setForm({
                                account: "",    // 账号
                                shopName: "",    // 店铺名称
                                bindShop: "",    // 绑定店铺
                                isorder: true,   // 是否接单
                                istodelivery: true,    // 是否配送
                                isbind: true,    // 是否绑定
                                bindtime: Date.now(),    // 绑定时间
                                failreason: "", // 失败原因
                                phone: "",      // 手机号
                                scoure: scoure,  // 来源
                                linkid: '',    // 链接id
                            })
                            }

                        }
                    >
                        绑定店铺
                    </Button>
                </div>

                <div>

                </div>
                <Tabs
                    onChange={(e) => {
                        if(e==='饿了么'){
                            setTitle('饿了么')
                            setScoure(0)
                        }
                        if(e==='美团'){
                            setTitle('美团')
                            setScoure(1)
                        }
                    }}
                    type="card"
                    items={
                        [
                            {
                                label: `饿了么`,
                                key: "饿了么",
                                children: <Table
                                    bordered
                                    className='rounded-none'
                                    columns={columns1}
                                    dataSource={bindData}
                                    pagination={{
                                        defaultPageSize: 5,
                                        total: bindData.length,
                                        showSizeChanger: true,
                                        pageSizeOptions: ['5', '10', '20'],
                                    }}
                                />,
                            },
                            {
                                label: `美团`,
                                key: "美团",
                                children: <Table
                                    bordered
                                    className='rounded-none'
                                    columns={columns1}
                                    dataSource={bindData}
                                    pagination={{
                                        defaultPageSize: 5,
                                        total: bindData.length,
                                        showSizeChanger: true,
                                        pageSizeOptions: ['5', '10', '20'],
                                    }}
                                />,
                            }
                        ]
                    }
                />

            </Card>

            <Modal
                style={{ borderRadius: 0 }}
                title={title+"绑定"}
                centered
                open={modalShow}
                footer={[
                    <Button key="back" onClick={() => {
                        setModalShow(false);
                    }}>取消</Button>,
                    <Button key="submit" type="primary" onClick={() => {
                        setModalShow(false);
                        if (form._id) {
                            handleUpdate();
                        } else {
                            handleAdd();
                        }
                    }}>
                        确认
                    </Button>
                ]}
                onCancel={() => {
                    setModalShow(false);
                }}
            >
                <BindForm form={form} setForm={setForm} 
                title={title}
                />
            </Modal>
        </div>
    );
};

export default Bind;
